const jwt = require("jsonwebtoken");
const tkconf = require("../config/index");
/**
 * token生成函数
 * @param {*} user
 * @param {*} serect
 * @param {*} time
 * @returns
 */
const addToken = (user, serect, time) => {
  // 创建token并导出
  const token = jwt.sign(
    {
      id: user.id,
      username: user.username,
    },
    serect,
    { expiresIn: time + "s" }
  );
  return token;
};
/**
 * token解析函数
 * @param {*} token
 * @returns
 */
const decodedToken = (token) => {
  const decoded = jwt.decode(token);
  return decoded;
};
/**
 * 验证对应的refreshToken
 * @param {*} refreshToken
 * @returns
 */
const verifyToken = (refreshToken) =>
  jwt.verify(refreshToken, tkconf.jwtRefrechSecretKey, (err, decode) =>
    err ? err : 1
  );

module.exports = {
  addToken,
  decodedToken,
  verifyToken,
};
